# -*- coding: utf-8 -*-
import sys
import os
import vlc
from PyQt6.QtWidgets import (QApplication, QMainWindow, QWidget, QVBoxLayout,
                           QPushButton, QHBoxLayout, QFileDialog, QSlider, QStyle,
                           QGridLayout, QLabel, QFrame, QScrollArea)
from PyQt6.QtCore import Qt, QTimer, QThread, pyqtSignal, QSize
from PyQt6.QtGui import QIcon, QColor, QPalette

class StyleSheet:
    MAIN_WINDOW = """
        QMainWindow {
            background-color: #1e1e1e;
        }
        QWidget {
            background-color: #2b2b2b;
            color: #ffffff;
        }
        QScrollArea {
            background-color: transparent;
            border: none;
        }
        QScrollBar:vertical {
            background: #2b2b2b;
            width: 12px;
            margin: 0px;
        }
        QScrollBar::handle:vertical {
            background: #404040;
            min-height: 20px;
            border-radius: 6px;
            margin: 2px;
        }
        QScrollBar::handle:vertical:hover {
            background: #4a4a4a;
        }
        QScrollBar::add-line:vertical, QScrollBar::sub-line:vertical {
            height: 0px;
        }
        QScrollBar::add-page:vertical, QScrollBar::sub-page:vertical {
            background: none;
        }
    """
    
    VIDEO_WIDGET = """
        QFrame {
            background-color: #2d2d2d;
            border-radius: 8px;
            padding: 2px;
        }
        QLabel {
            color: #ffffff;
            font-size: 12px;
            padding: 2px;
            margin: 0px;
        }
        QPushButton {
            background-color: #3a3a3a;
            border: none;
            border-radius: 10px;
            padding: 2px;
            min-width: 20px;
            min-height: 20px;
            margin: 0px;
        }
        QPushButton:hover {
            background-color: #4a4a4a;
        }
        QPushButton:pressed {
            background-color: #555555;
        }
        QSlider {
            margin: 0px;
            padding: 0px;
        }
        QSlider::groove:horizontal {
            border: 1px solid #999999;
            height: 3px;
            background: #4a4a4a;
            margin: 1px 0;
            border-radius: 2px;
        }
        QSlider::handle:horizontal {
            background: #ffffff;
            border: none;
            width: 8px;
            margin: -3px 0;
            border-radius: 4px;
        }
        QSlider::handle:horizontal:hover {
            background: #e0e0e0;
            width: 10px;
            margin: -4px 0;
        }
    """
    
    CONTROL_BUTTONS = """
        QPushButton {
            background-color: #3a3a3a;
            color: white;
            border: none;
            border-radius: 5px;
            padding: 8px 15px;
            font-size: 14px;
            min-width: 100px;
        }
        QPushButton:hover {
            background-color: #4a4a4a;
        }
        QPushButton:pressed {
            background-color: #555555;
        }
    """

class VideoLoaderThread(QThread):
    """视频加载线程"""
    finished = pyqtSignal(list)
    
    def __init__(self, folder_path):
        super().__init__()
        self.folder_path = folder_path
    
    def run(self):
        video_files = []
        for file in os.listdir(self.folder_path):
            if file.lower().endswith(('.mp4', '.avi', '.mkv', '.mov')):
                video_files.append(os.path.join(self.folder_path, file))
        self.finished.emit(video_files)

class VideoWidget(QFrame):
    def __init__(self, video_path, parent=None):
        super().__init__(parent)
        self.video_path = video_path
        self.setStyleSheet(StyleSheet.VIDEO_WIDGET)
        
        # 设置阴影效果
        self.setFrameShape(QFrame.Shape.StyledPanel)
        self.setFrameShadow(QFrame.Shadow.Raised)
        
        # 创建VLC实例
        self.instance = vlc.Instance()
        self.mediaplayer = self.instance.media_player_new()
        
        # 初始化标志
        self.is_initialized = False
        self.retry_count = 0
        self.one_third_position = 0
        
        # 全屏状态标志
        self.is_fullscreen = False
        self.normal_geometry = None
        
        # 创建布局
        self.layout = QVBoxLayout(self)
        self.layout.setContentsMargins(5, 5, 5, 5)
        self.layout.setSpacing(2)
        
        # 创建视频显示区域
        self.video_frame = QWidget(self)
        self.video_frame.setStyleSheet("background-color: black; border-radius: 5px;")
        self.video_frame.setMinimumSize(640, 360)  # 16:9比例
        self.layout.addWidget(self.video_frame, 4)
        
        # 添加播放功能区
        self.playback_controls = QWidget(self.video_frame)
        self.playback_controls.setStyleSheet("""
            QWidget {
                background-color: rgba(0, 0, 0, 150);
                border-radius: 5px;
            }
            QPushButton {
                background-color: transparent;
                border: none;
                color: white;
            }
            QPushButton:hover {
                background-color: rgba(255, 255, 255, 30);
            }
        """)
        self.playback_controls.hide()
        
        # 创建播放功能区布局
        self.playback_controls_layout = QVBoxLayout(self.playback_controls)
        self.playback_controls_layout.setContentsMargins(5, 5, 5, 5)
        self.playback_controls_layout.setSpacing(5)
        
        # 添加播放/暂停按钮
        self.overlay_play_button = QPushButton()
        self.overlay_play_button.setIcon(self.style().standardIcon(QStyle.StandardPixmap.SP_MediaPlay))
        self.overlay_play_button.setIconSize(QSize(48, 48))
        self.overlay_play_button.clicked.connect(self.play_pause)
        self.playback_controls_layout.addWidget(self.overlay_play_button, alignment=Qt.AlignmentFlag.AlignCenter)
        
        # 设置播放功能区位置
        self.playback_controls.setGeometry(
            (self.video_frame.width() - 100) // 2,
            (self.video_frame.height() - 100) // 2,
            100,
            100
        )
        
        # 启用鼠标追踪
        self.video_frame.setMouseTracking(True)
        
        # 鼠标进入和离开事件
        self.video_frame.enterEvent = self.show_playback_controls
        self.video_frame.leaveEvent = self.hide_playback_controls
        
        # 添加双击事件支持
        self.video_frame.mouseDoubleClickEvent = self.toggle_fullscreen
        
        # 添加文件名标签
        self.name_label = QLabel(os.path.basename(video_path))
        self.name_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
        self.name_label.setStyleSheet("""
            background-color: transparent;
            color: white;
            font-size: 12px;
        """)
        self.name_label.setMaximumHeight(20)
        self.layout.addWidget(self.name_label)
        
        # 控制按钮和进度条布局
        self.controls_layout = QVBoxLayout()
        self.controls_layout.setContentsMargins(2, 0, 2, 2)  # 减小控制区域边距
        self.controls_layout.setSpacing(2)  # 减小间距
        
        # 进度条
        self.progress_layout = QHBoxLayout()
        self.progress_layout.setContentsMargins(0, 0, 0, 0)  # 移除进度条布局的边距
        self.time_label = QLabel("00:00")
        self.time_label.setStyleSheet("color: white; font-size: 9px;")  # 减小字体
        self.progress_layout.addWidget(self.time_label)
        
        self.position_slider = QSlider(Qt.Orientation.Horizontal)
        self.position_slider.setStyleSheet("""
            QSlider::groove:horizontal {
                border: 1px solid #999999;
                height: 2px;  /* 减小进度条高度 */
                background: #4a4a4a;
                margin: 1px 0;
                border-radius: 1px;  /* 减小圆角 */
            }
            QSlider::sub-page:horizontal {
                background: #0078d4;  /* 已播放部分的颜色 */
                border: 1px solid #0078d4;
                height: 2px;
                border-radius: 1px;
            }
            QSlider::handle:horizontal {
                background: #ffffff;
                border: none;  /* 移除边框 */
                width: 8px;  /* 减小手柄大小 */
                margin: -3px 0;
                border-radius: 4px;
            }
            QSlider::handle:horizontal:hover {
                background: #e0e0e0;
                width: 10px;  /* 悬停时略微增大 */
                margin: -4px 0;
            }
            QSlider::handle:horizontal:pressed {
                background: #cccccc;
                width: 10px;
                margin: -4px 0;
            }
        """)
        self.position_slider.setMaximumHeight(10)  # 限制进度条的最大高度
        self.position_slider.setMaximum(1000)
        self.position_slider.sliderMoved.connect(self.set_position)
        self.position_slider.sliderPressed.connect(self.slider_pressed)
        self.position_slider.sliderReleased.connect(self.slider_released)
        self.position_slider.mousePressEvent = self.slider_mouse_press
        self.position_slider.mouseReleaseEvent = self.slider_mouse_release
        self.progress_layout.addWidget(self.position_slider)
        
        self.duration_label = QLabel("00:00")
        self.duration_label.setStyleSheet("color: white; font-size: 9px;")  # 减小字体
        self.progress_layout.addWidget(self.duration_label)
        
        self.controls_layout.addLayout(self.progress_layout)
        
        # 播放按钮布局
        self.buttons_layout = QHBoxLayout()
        self.buttons_layout.setSpacing(2)  # 减小整体按钮布局间距
        self.buttons_layout.setContentsMargins(0, 0, 0, 0)  # 移除按钮布局的边距
        
        # 添加左侧弹性空间，比右侧多一些，这样按钮组会偏右
        self.buttons_layout.addStretch(2)
        
        # 播放控制按钮组
        self.playback_container = QWidget()
        self.playback_layout = QHBoxLayout(self.playback_container)
        self.playback_layout.setContentsMargins(0, 0, 0, 0)
        self.playback_layout.setSpacing(15)  # 增加控制按钮之间的间距
        
        # 设置所有按钮的统一大小
        button_size = 24
        
        # 快退按钮
        self.rewind_button = QPushButton()
        self.rewind_button.setFixedSize(button_size, button_size)
        self.rewind_button.setIcon(self.style().standardIcon(QStyle.StandardPixmap.SP_MediaSkipBackward))
        self.rewind_button.clicked.connect(lambda: self.seek_relative(-15000))  # 快退15秒
        self.playback_layout.addWidget(self.rewind_button)
        
        # 播放按钮
        self.play_button = QPushButton()
        self.play_button.setFixedSize(button_size, button_size)
        self.play_button.setIcon(self.style().standardIcon(QStyle.StandardPixmap.SP_MediaPlay))
        self.play_button.clicked.connect(self.play_pause)
        self.playback_layout.addWidget(self.play_button)
        
        # 快进按钮
        self.forward_button = QPushButton()
        self.forward_button.setFixedSize(button_size, button_size)
        self.forward_button.setIcon(self.style().standardIcon(QStyle.StandardPixmap.SP_MediaSkipForward))
        self.forward_button.clicked.connect(lambda: self.seek_relative(30000))  # 快进30秒
        self.playback_layout.addWidget(self.forward_button)
        
        # 添加播放控制按钮组到主布局
        self.buttons_layout.addWidget(self.playback_container)
        
        # 添加中间弹性空间，比左侧小，这样按钮组会偏右
        self.buttons_layout.addStretch(1)
        
        # 音量控制部分
        self.volume_container = QWidget()
        self.volume_layout = QHBoxLayout(self.volume_container)
        self.volume_layout.setContentsMargins(0, 0, 0, 0)
        self.volume_layout.setSpacing(5)
        
        # 静音按钮
        self.mute_button = QPushButton()
        self.mute_button.setIcon(self.style().standardIcon(QStyle.StandardPixmap.SP_MediaVolume))
        self.mute_button.clicked.connect(self.toggle_mute)
        self.mute_button.setFixedSize(button_size, button_size)  # 使用相同的按钮大小
        self.volume_layout.addWidget(self.mute_button)
        
        # 音量滑块
        self.volume_slider = QSlider(Qt.Orientation.Horizontal)
        self.volume_slider.setStyleSheet("""
            QSlider::groove:horizontal {
                border: 1px solid #999999;
                height: 3px;
                background: #4a4a4a;
                margin: 2px 0;
                border-radius: 2px;
            }
            QSlider::sub-page:horizontal {
                background: #22a540;
                border: 1px solid #22a540;
                height: 3px;
                border-radius: 2px;
            }
            QSlider::handle:horizontal {
                background: #ffffff;
                border: none;
                width: 8px;
                margin: -3px 0;
                border-radius: 4px;
            }
            QSlider::handle:horizontal:hover {
                background: #e0e0e0;
                width: 10px;
                margin: -4px 0;
            }
        """)
        self.volume_slider.setMaximum(100)
        self.volume_slider.setValue(0)  # 初始音量为0
        self.volume_slider.setFixedWidth(60)  # 设置滑块宽度
        self.volume_slider.valueChanged.connect(self.set_volume)
        self.volume_layout.addWidget(self.volume_slider)
        
        # 添加音量控制到主布局
        self.buttons_layout.addWidget(self.volume_container)
        
        # 添加全屏按钮
        self.fullscreen_button = QPushButton()
        self.fullscreen_button.setIcon(self.style().standardIcon(QStyle.StandardPixmap.SP_TitleBarMaxButton))
        self.fullscreen_button.clicked.connect(self.toggle_fullscreen)
        self.fullscreen_button.setFixedSize(button_size, button_size)
        self.buttons_layout.addWidget(self.fullscreen_button)
        
        # 添加控制布局到主布局
        self.controls_layout.addLayout(self.buttons_layout)
        self.layout.addLayout(self.controls_layout)
        
        # 初始化播放器
        self.setup_player()
        # 延迟自动播放，给予更多时间进行初始化
        QTimer.singleShot(1000, self.delayed_auto_play)
        
        # 创建定时器更新进度条
        self.update_timer = QTimer(self)
        self.update_timer.setInterval(100)
        self.update_timer.timeout.connect(self.update_progress)
        
        # 标记是否正在拖动进度条
        self.is_dragging = False
        
        # 添加音量状态变量
        self.is_muted = True
        self.last_volume = 50

    def slider_mouse_press(self, event):
        """处理进度条点击事件"""
        if event.button() == Qt.MouseButton.LeftButton:
            self.is_dragging = True
            if self.mediaplayer.is_playing():
                self.mediaplayer.pause()
                self.update_timer.stop()
            
            # 立即更新位置
            value = QStyle.sliderValueFromPosition(
                self.position_slider.minimum(),
                self.position_slider.maximum(),
                event.pos().x(),
                self.position_slider.width()
            )
            self.position_slider.setValue(value)
            self.set_position()
        
        # 调用原始的mousePressEvent
        QSlider.mousePressEvent(self.position_slider, event)

    def slider_pressed(self):
        """进度条被按下"""
        self.is_dragging = True
        if self.mediaplayer.is_playing():
            self.mediaplayer.pause()
            self.update_timer.stop()

    def slider_released(self):
        """进度条被释放"""
        self.is_dragging = False
        self.set_position()
        if not self.mediaplayer.is_playing():
            self.mediaplayer.play()
            self.update_timer.start()

    def slider_mouse_release(self, event):
        """处理进度条释放事件"""
        if event.button() == Qt.MouseButton.LeftButton:
            self.is_dragging = False
            self.set_position()
            if not self.mediaplayer.is_playing():
                self.mediaplayer.play()
                self.update_timer.start()
        
        # 调用原始的mouseReleaseEvent
        QSlider.mouseReleaseEvent(self.position_slider, event)

    def format_time(self, milliseconds):
        """将毫秒转换为时间格式字符串"""
        seconds = int(milliseconds / 1000)
        minutes = seconds // 60
        seconds = seconds % 60
        return f"{minutes:02d}:{seconds:02d}"

    def update_progress(self):
        """更新进度条和时间标签"""
        if not self.mediaplayer.is_playing() or self.is_dragging:
            return
        
        # 更新进度条
        length = self.mediaplayer.get_length()
        if length > 0:
            position = int(self.mediaplayer.get_position() * 1000)
            if not self.is_dragging:  # 只在非拖动状态更新滑块位置
                self.position_slider.setValue(position)
            
            # 更新时间标签
            current_time = int(length * self.mediaplayer.get_position())
            self.time_label.setText(self.format_time(current_time))
            self.duration_label.setText(self.format_time(length))

    def delayed_auto_play(self):
        """延迟自动播放，确保视频已经完全加载"""
        if not self.is_initialized:
            # 如果还没初始化完成，继续等待
            if self.retry_count < 5:
                self.retry_count += 1
                QTimer.singleShot(500, self.delayed_auto_play)
                return
        
        # 开始播放并设置位置
        self.mediaplayer.play()
        # self.mediaplayer.setLoopCount(-1)  # -1 表示无限循环
        QTimer.singleShot(100, self.force_set_position)
    
    def force_set_position(self):
        """强制设置播放位置"""
        # 设置播放位置到三分之一处
        self.mediaplayer.set_time(self.one_third_position)
        
        # 强制更新进度条位置
        total_time = self.mediaplayer.get_length()
        if total_time > 0:
            new_position = self.one_third_position / total_time
            self.position_slider.setValue(int(new_position * 1000))
            # 更新时间标签
            self.time_label.setText(self.format_time(self.one_third_position))
            self.duration_label.setText(self.format_time(total_time))
        
        # 启动进度条更新定时器
        self.update_timer.start()
        
        # 更新播放按钮图标
        self.play_button.setIcon(self.style().standardIcon(QStyle.StandardPixmap.SP_MediaPause))
        self.overlay_play_button.setIcon(self.style().standardIcon(QStyle.StandardPixmap.SP_MediaPause))

    def setup_player(self):
        """设置播放器"""
        self.media = self.instance.media_new(self.video_path)
        self.mediaplayer.set_media(self.media)
        
        # 设置事件管理器来处理视频结束事件
        self.event_manager = self.mediaplayer.event_manager()
        self.event_manager.event_attach(vlc.EventType.MediaPlayerEndReached, self.on_media_end)
        
        # 等待媒体被解析
        self.media.parse_with_options(vlc.MediaParseFlag.local, 0)
        
        # 使用定时器检查解析状态
        self.parse_timer = QTimer(self)
        self.parse_timer.setInterval(100)
        self.parse_timer.timeout.connect(self.check_parse_status)
        self.parse_timer.start()
        
        if sys.platform.startswith('win'):
            self.mediaplayer.set_hwnd(int(self.video_frame.winId()))
        elif sys.platform.startswith('linux'):
            self.mediaplayer.set_xwindow(int(self.video_frame.winId()))
        elif sys.platform.startswith('darwin'):
            self.mediaplayer.set_nsobject(int(self.video_frame.winId()))

        # 设置视频缩放模式，让视频填满整个窗口
        self.mediaplayer.video_set_scale(0)  # 0 表示自动缩放，尝试填满窗口
        self.mediaplayer.video_set_aspect_ratio(None)  # 不强制设置宽高比
        
        # 初始化为静音
        self.mediaplayer.audio_set_volume(0)

    def check_parse_status(self):
        """检查媒体解析状态"""
        if self.media.get_parsed_status() == vlc.MediaParsedStatus.done:
            self.parse_timer.stop()
            
            # 计算三分之一位置
            total_time = self.media.get_duration()
            self.one_third_position = total_time // 3
            
            # 标记初始化完成
            self.is_initialized = True

    def play_pause(self):
        if self.mediaplayer.is_playing():
            self.mediaplayer.pause()
            self.play_button.setIcon(self.style().standardIcon(QStyle.StandardPixmap.SP_MediaPlay))
            self.update_timer.stop()
        else:
            self.mediaplayer.play()
            self.play_button.setIcon(self.style().standardIcon(QStyle.StandardPixmap.SP_MediaPause))
            self.update_timer.start()
            
    def stop(self):
        """停止播放"""
        self.mediaplayer.stop()
        self.play_button.setIcon(self.style().standardIcon(QStyle.StandardPixmap.SP_MediaPlay))
        self.update_timer.stop()
        self.position_slider.setValue(0)
        self.time_label.setText("00:00")
    
    def set_position(self):
        """设置播放位置"""
        pos = self.position_slider.value()
        self.mediaplayer.set_position(pos / 1000.0)

    def toggle_mute(self):
        """切换静音状态"""
        if self.is_muted:
            # 取消静音
            self.mediaplayer.audio_set_volume(self.last_volume)
            self.volume_slider.setValue(self.last_volume)
            self.mute_button.setIcon(self.style().standardIcon(QStyle.StandardPixmap.SP_MediaVolume))
        else:
            # 静音
            self.last_volume = self.volume_slider.value()
            self.mediaplayer.audio_set_volume(0)
            self.volume_slider.setValue(0)
            self.mute_button.setIcon(self.style().standardIcon(QStyle.StandardPixmap.SP_MediaVolumeMuted))
        self.is_muted = not self.is_muted

    def set_volume(self, volume):
        """设置音量"""
        self.mediaplayer.audio_set_volume(volume)
        # 更新静音按钮状态
        if volume == 0:
            self.mute_button.setIcon(self.style().standardIcon(QStyle.StandardPixmap.SP_MediaVolumeMuted))
            self.is_muted = True
        else:
            self.mute_button.setIcon(self.style().standardIcon(QStyle.StandardPixmap.SP_MediaVolume))
            self.is_muted = False
            self.last_volume = volume

    def seek_relative(self, offset_ms):
        """相对当前位置快进或快退
        Args:
            offset_ms: 偏移毫秒数，正数表示快进，负数表示快退
        """
        # 获取当前时间
        current_time = self.mediaplayer.get_time()
        if current_time is None:
            return
            
        # 获取总时长
        total_time = self.mediaplayer.get_length()
        if total_time <= 0:
            return
            
        # 计算新的时间位置
        new_time = max(0, min(total_time, current_time + offset_ms))
        
        # 如果视频已经结束，需要先重新开始播放
        if not self.mediaplayer.is_playing():
            self.mediaplayer.play()
            self.play_button.setIcon(self.style().standardIcon(QStyle.StandardPixmap.SP_MediaPause))
            self.overlay_play_button.setIcon(self.style().standardIcon(QStyle.StandardPixmap.SP_MediaPause))
            self.update_timer.start()
        
        # 设置新的播放位置
        self.mediaplayer.set_time(int(new_time))
        
        # 更新进度条
        if total_time > 0:
            new_position = new_time / total_time
            self.position_slider.setValue(int(new_position * 1000))

    def toggle_fullscreen(self, event=None):
        """切换全屏状态"""
        if not self.is_fullscreen:
            # 保存当前几何信息
            self.normal_geometry = self.geometry()
            # 进入全屏
            self.setWindowFlags(Qt.WindowType.Window)
            self.showFullScreen()
            self.is_fullscreen = True
            self.fullscreen_button.setIcon(self.style().standardIcon(QStyle.StandardPixmap.SP_TitleBarNormalButton))
        else:
            # 退出全屏
            self.showNormal()
            self.setWindowFlags(Qt.WindowType.Widget)
            if self.normal_geometry:
                self.setGeometry(self.normal_geometry)
            self.is_fullscreen = False
            self.fullscreen_button.setIcon(self.style().standardIcon(QStyle.StandardPixmap.SP_TitleBarMaxButton))
        
        # 确保窗口显示在最前面
        self.show()
        self.raise_()
        self.activateWindow()

    def show_playback_controls(self, event):
        """显示播放功能区"""
        self.playback_controls.show()

    def hide_playback_controls(self, event):
        """隐藏播放功能区"""
        self.playback_controls.hide()

    def resizeEvent(self, event):
        """处理窗口大小改变事件"""
        super().resizeEvent(event)
        # 更新播放功能区位置
        self.playback_controls.setGeometry(
            (self.video_frame.width() - 10) // 2,
            (self.video_frame.height() - 100) // 2,
            100,
            100
        )

    def on_media_end(self, event):
        """处理视频播放结束事件"""
        # 使用 QTimer 确保在主线程中执行
        QTimer.singleShot(0, self.restart_playback)
    
    def restart_playback(self):
        """重新开始播放视频"""
        self.mediaplayer.stop()
        self.mediaplayer.play()
        self.mediaplayer.set_time(self.one_third_position)  # 从三分之一处开始播放
        
        # 更新进度条和按钮状态
        self.update_timer.start()
        self.play_button.setIcon(self.style().standardIcon(QStyle.StandardPixmap.SP_MediaPause))
        self.overlay_play_button.setIcon(self.style().standardIcon(QStyle.StandardPixmap.SP_MediaPause))

class VideoPlayer(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("MyPlayer")
        self.setGeometry(50, 50, 2400, 1600)
        self.setStyleSheet(StyleSheet.MAIN_WINDOW)
        
        # 创建主窗口部件
        self.central_widget = QWidget(self)
        self.setCentralWidget(self.central_widget)
        
        # 创建主布局
        self.main_layout = QVBoxLayout(self.central_widget)
        self.main_layout.setContentsMargins(20, 20, 20, 20)
        self.main_layout.setSpacing(15)
        
        # 创建滚动区域
        self.scroll_area = QScrollArea()
        self.scroll_area.setWidgetResizable(True)
        self.scroll_area.setStyleSheet("""
            QScrollArea {
                background-color: transparent;
                border: none;
            }
            QScrollBar:vertical {
                background: #2b2b2b;
                width: 12px;
                margin: 0px;
            }
            QScrollBar::handle:vertical {
                background: #404040;
                min-height: 20px;
                border-radius: 6px;
                margin: 2px;
            }
            QScrollBar::handle:vertical:hover {
                background: #4a4a4a;
            }
            QScrollBar::add-line:vertical, QScrollBar::sub-line:vertical {
                height: 0px;
            }
            QScrollBar::add-page:vertical, QScrollBar::sub-page:vertical {
                background: none;
            }
        """)
        
        # 创建一个包含视频网格的滚动区域容器
        self.videos_container = QWidget()
        self.videos_layout = QVBoxLayout(self.videos_container)
        self.videos_layout.setContentsMargins(0, 0, 0, 0)
        
        # 创建网格布局用于放置视频窗口
        self.grid_layout = QGridLayout()
        self.grid_layout.setSpacing(15)
        self.videos_layout.addLayout(self.grid_layout)
        
        # 添加一个弹性空间，使视频网格保持在顶部
        self.videos_layout.addStretch()
        
        # 设置滚动区域的内容
        self.scroll_area.setWidget(self.videos_container)
        
        # 将滚动区域添加到主布局
        self.main_layout.addWidget(self.scroll_area, stretch=1)
        
        # 创建底部控制栏容器
        self.bottom_container = QWidget()
        self.bottom_container.setStyleSheet("""
            QWidget {
                background-color: #1e1e1e;
                border-radius: 10px;
                padding: 10px;
            }
        """)
        self.bottom_layout = QHBoxLayout(self.bottom_container)
        self.bottom_layout.setContentsMargins(20, 10, 20, 10)
        self.bottom_layout.setSpacing(15)
        
        # 在底部控制栏左侧添加一个弹性空间
        self.bottom_layout.addStretch()
        
        # 选择文件夹按钮
        self.open_folder_button = QPushButton("选择文件夹")
        self.open_folder_button.setStyleSheet(StyleSheet.CONTROL_BUTTONS)
        self.open_folder_button.clicked.connect(self.open_folder)
        self.bottom_layout.addWidget(self.open_folder_button)
        
        # 全部播放按钮
        self.play_all_button = QPushButton("全部播放")
        self.play_all_button.setStyleSheet(StyleSheet.CONTROL_BUTTONS)
        self.play_all_button.clicked.connect(self.play_all_videos)
        self.bottom_layout.addWidget(self.play_all_button)
        
        # 全部停止按钮
        self.stop_all_button = QPushButton("全部停止")
        self.stop_all_button.setStyleSheet(StyleSheet.CONTROL_BUTTONS)
        self.stop_all_button.clicked.connect(self.stop_all_videos)
        self.bottom_layout.addWidget(self.stop_all_button)
        
        # 在底部控制栏右侧添加一个弹性空间
        self.bottom_layout.addStretch()
        
        # 将底部控制栏添加到主布局
        self.main_layout.addWidget(self.bottom_container)
        
        self.video_widgets = []
        
    def open_folder(self):
        dialog = QFileDialog(self)
        folder_path = dialog.getExistingDirectory(self, "选择文件夹")
        if folder_path:
            # 使用线程加载视频
            self.loader_thread = VideoLoaderThread(folder_path)
            self.loader_thread.finished.connect(self.on_videos_loaded)
            self.loader_thread.start()
    
    def on_videos_loaded(self, video_files):
        # 清除现有的视频窗口
        for widget in self.video_widgets:
            widget.setParent(None)
        self.video_widgets.clear()
        
        # 创建视频窗口
        cols = 3  # 每行显示3个视频
        for i, video_path in enumerate(video_files):
            video_widget = VideoWidget(video_path)
            self.video_widgets.append(video_widget)
            row = i // cols
            col = i % cols
            self.grid_layout.addWidget(video_widget, row, col)
    
    def play_all_videos(self):
        for widget in self.video_widgets:
            if not widget.mediaplayer.is_playing():
                widget.play_pause()
    
    def stop_all_videos(self):
        for widget in self.video_widgets:
            if widget.mediaplayer.is_playing():
                widget.play_pause()

    def setup_instance(self):
        """初始化VLC实例"""
        # 启用NVIDIA GPU硬件加速解码
        self.instance = vlc.Instance('--avcodec-hw=dxva2',  # DirectX Video Acceleration 2.0
                                   '--gpu-display',          # 启用GPU显示
                                   '--no-avcodec-dr',        # 禁用直接渲染以提高兼容性
                                   '--network-caching=1000') # 设置1秒缓冲

if __name__ == '__main__':
    app = QApplication(sys.argv)
    
    # 设置应用程序级别的样式
    app.setStyle('Fusion')  # 使用Fusion风格，这是跨平台最一致的风格
    
    player = VideoPlayer()
    player.show()
    
    # 自动加载指定文件夹中的视频
    default_folder = r"D:\nginx\temp\home\wonder\resources\video"
    if os.path.exists(default_folder):
        # 使用线程加载视频
        player.loader_thread = VideoLoaderThread(default_folder)
        player.loader_thread.finished.connect(player.on_videos_loaded)
        player.loader_thread.start()
    
    sys.exit(app.exec()) 